<template>
  <div class="goods-type-manage">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h3 class="page-title">物品类型管理</h3>
        <p class="page-subtitle">管理系统中的所有物品分类类型</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-refresh" @click="refreshData" class="action-btn">
          <span>刷新数据</span>
        </el-button>
      </div>
    </div>

    <!-- 查询区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" class="search-form">
        <el-form-item label="类别名称">
          <el-input v-model="searchForm.categoryName" placeholder="请输入类别名称" clearable style="width: 100%; max-width: 300px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch" class="action-btn">
            <span>查询</span>
          </el-button>
          <el-button @click="resetSearch" class="action-btn">
            <span>重置</span>
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="action-buttons" style="margin: 16px 0;">
      <el-button type="success" icon="el-icon-plus" @click="handleAdd" class="action-btn">
        <span>新增类型</span>
      </el-button>
      <el-button type="danger" icon="el-icon-delete" @click="handleDelete" :disabled="selectedRows.length === 0" class="action-btn">
        <span>批量删除</span>
      </el-button>
      <el-button type="info" icon="el-icon-upload" @click="handleImport" class="action-btn">
        <span>导入数据</span>
      </el-button>
      <el-button type="info" icon="el-icon-download" @click="handleExport" class="action-btn">
        <span>导出数据</span>
      </el-button>
    </div>

    <!-- 数据表格区域 -->
    <el-card shadow="hover" class="table-card">
      <div class="table-header">
        <div class="table-title">类型列表</div>
      </div>
      <el-table :data="tableData" border stripe highlight-current-row @selection-change="handleSelectionChange"
        element-loading-text="数据加载中..." :loading="loading" style="width: 100%;">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="categoryId" label="ID" align="center" width="80" />
        <el-table-column prop="categoryName" label="类别名称" align="center" min-width="180" />
        <el-table-column label="图标" align="center" width="160">
          <template #default="scope">
            <div class="icon-container">
              <el-select v-model="scope.row.icon" placeholder="选择图标" size="small"
                @change="updateIcon(scope.row)" style="width: 140px;">
                <el-option value="" label="无图标" />
                <el-option v-for="(icon, index) in iconList" :key="index" :label="icon" :value="index" />
              </el-select>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="240">
          <template #default="scope">
            <el-button type="primary" size="mini" @click="handleDetail(scope.row)" icon="el-icon-view" class="action-btn-small">
              <span>详情</span>
            </el-button>
            <el-button type="warning" size="mini" @click="handleEdit(scope.row)" icon="el-icon-edit" class="action-btn-small">
              <span>修改</span>
            </el-button>
            <el-button type="danger" size="mini" @click="handleRowDelete(scope.row)" icon="el-icon-delete" class="action-btn-small">
              <span>删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" title="物品类型管理" width="40%" :before-close="handleClose">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="类别名称" prop="categoryName">
          <el-input v-model="formData.categoryName" placeholder="请输入类别名称" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-select v-model="formData.icon" placeholder="请选择图标">
            <el-option value="" label="无图标" />
            <el-option v-for="(icon, index) in iconList" :key="index" :label="icon" :value="index" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveData">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="物品类型详情" width="40%" :before-close="handleCloseDetail">
      <el-form :model="detailData" label-width="120px">
        <el-form-item label="类别ID">
          <el-input v-model="detailData.categoryId" disabled />
        </el-form-item>
        <el-form-item label="类别名称">
          <el-input v-model="detailData.categoryName" disabled />
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="detailData.icon" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="detailVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  reactive,
  toRefs,
  nextTick
} from 'vue'
import {
  ElMessage,
  ElMessageBox,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElButton
} from 'element-plus'

// 搜索表单
const searchForm = reactive({
  categoryName: ''
})
const searchFormRef = ref(null)

// 表格数据
const tableData = ref([])
const selectedRows = ref([])
const loading = ref(false)

// 对话框状态
const dialogVisible = ref(false)
const detailVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const formRef = ref(null)

// 表单数据
const formData = reactive({
  categoryId: null,
  categoryName: '',
  icon: ''
})

// 详情数据
const detailData = reactive({
  categoryId: '',
  categoryName: '',
  icon: ''
})

// 表单验证规则
const rules = reactive({
  categoryName: [{
      required: true,
      message: '请输入类别名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度在 2 到 20 个字符',
      trigger: 'blur'
    }
  ],
  icon: [{
    required: true,
    message: '请选择图标',
    trigger: 'change'
  }]
})

// 图标列表（使用 Element Plus 图标类名）
const iconList = [
  'circle-plus', 'circle-check', 'circle-close', 'star-on', 'star-off',
  'shopping-cart-full', 'document', 'picture', 'video-play', 'location'
]

// 更新图标
const updateIcon = async (row) => {
  console.log('更新图标', row)
  try {
    const response = await fetch(`http://172.20.10.2:8080/api/Category/${row.categoryId}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        icon: row.icon
      })
    })
    if (response.ok) {
      const result = await response.json()
      ElMessage.success(result.message || '图标更新成功')
    } else {
      const errorData = await response.json()
      ElMessage.error(errorData.message || '图标更新失败')
    }
  } catch (error) {
    console.error('更新图标失败:', error)
    ElMessage.error('网络错误，图标更新失败')
  }
}

// 获取数据
const fetchCategoryData = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = new URLSearchParams()
    if (searchForm.categoryName) {
      params.append('categoryName', searchForm.categoryName)
    }

    const response = await fetch(`http://172.20.10.2:8080/api/Category/getAll?${params.toString()}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    if (response.ok) {
      const result = await response.json()
      if (result.code === 200 && result.data) {
        tableData.value = result.data.map(item => ({
          ...item
        }))
      } else {
        throw new Error(result.message || '获取数据失败')
      }
    } else {
      throw new Error(`HTTP 错误！状态码：${response.status}`)
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 查询按钮事件
const handleSearch = () => {
  console.log('查询按钮被点击')
  fetchCategoryData()
}

// 重置搜索
const resetSearch = () => {
  console.log('重置按钮被点击')
  searchForm.categoryName = ''
  if (searchFormRef.value) {
    searchFormRef.value.resetFields()
  }
  fetchCategoryData()
}

// 新增按钮事件
const handleAdd = () => {
  console.log('新增按钮被点击')
  dialogType.value = 'add'
  formData.categoryId = null
  formData.categoryName = ''
  formData.icon = ''
  
  // 使用nextTick确保DOM更新完成
  nextTick(() => {
    dialogVisible.value = true
  })
}

// 批量删除
const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    return ElMessage.warning('请选择要删除的数据')
  }

  const ids = selectedRows.value.map(item => item.categoryId).join(',')

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
    '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await fetch(`http://172.20.10.2:8080/api/Category/deleteBatch`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          ids
        })
      })

      if (response.ok) {
        const result = await response.json()
        if (result.code === 200) {
          ElMessage.success(result.message || '删除成功')
          fetchCategoryData()
          selectedRows.value = []
        } else {
          throw new Error(result.message || '删除失败')
        }
      } else {
        throw new Error(`HTTP 错误！状态码：${response.status}`)
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 表格多选事件
const handleSelectionChange = (val) => {
  selectedRows.value = val
}

// 详情
const handleDetail = (row) => {
  console.log('详情按钮被点击', row)
  detailData.categoryId = row.categoryId
  detailData.categoryName = row.categoryName
  detailData.icon = row.icon ? iconList[row.icon] : '无图标'
  
  // 使用nextTick确保DOM更新完成
  nextTick(() => {
    detailVisible.value = true
  })
}

// 修改
const handleEdit = (row) => {
  console.log('修改按钮被点击', row)
  dialogType.value = 'edit'
  formData.categoryId = row.categoryId
  formData.categoryName = row.categoryName
  formData.icon = row.icon
  
  // 使用nextTick确保DOM更新完成
  nextTick(() => {
    dialogVisible.value = true
  })
}

// 单行删除
const handleRowDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除 ${row.categoryName} 吗？`,
    '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await fetch(`http://172.20.10.2:8080/api/Category/${row.categoryId}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json'
        }
      })

      if (response.ok) {
        const result = await response.json()
        if (result.code === 200) {
          ElMessage.success(result.message || '删除成功')
          fetchCategoryData()
        } else {
          throw new Error(result.message || '删除失败')
        }
      } else {
        throw new Error(`HTTP 错误！状态码：${response.status}`)
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 保存数据（新增/编辑）
const saveData = () => {
  console.log('保存数据被调用')
  if (!formRef.value) return
  
  formRef.value.validate(async (valid) => {
    if (!valid) return false

    try {
      let response
      let message

      if (dialogType.value === 'add') {
        // 新增
        response = await fetch('http://172.20.10.2:8080/api/Category/add', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            categoryName: formData.categoryName,
            icon: formData.icon
          })
        })
        message = '新增成功'
      } else {
        // 编辑
        response = await fetch(`http://172.20.10.2:8080/api/Category/${formData.categoryId}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            categoryName: formData.categoryName,
            icon: formData.icon
          })
        })
        message = '更新成功'
      }

      if (response.ok) {
        const result = await response.json()
        if (result.code === 200) {
          ElMessage.success(result.message || message)
          dialogVisible.value = false
          fetchCategoryData()
        } else {
          throw new Error(result.message || (dialogType.value === 'add' ? '新增失败' : '更新失败'))
        }
      } else {
        throw new Error(`HTTP 错误！状态码：${response.status}`)
      }
    } catch (error) {
      console.error(dialogType.value === 'add' ? '新增失败' : '更新失败', error)
      ElMessage.error(error.message || (dialogType.value === 'add' ? '新增失败' : '更新失败'))
    }
  })
}

// 关闭对话框
const handleClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  dialogVisible.value = false
}

// 关闭详情对话框
const handleCloseDetail = () => {
  detailVisible.value = false
}

// 刷新数据
const refreshData = () => {
  fetchCategoryData()
}

// 导入/导出功能（仅显示提示）
const handleImport = () => {
  ElMessage.info('导入功能开发中...')
}

const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 组件挂载后初始化数据
onMounted(() => {
  fetchCategoryData()
})
</script>

<style scoped>
	/* 基础变量定义 */
	:root {
		--primary-color: #409EFF;
		--success-color: #67C23A;
		--warning-color: #E6A23C;
		--danger-color: #F56C6C;
		--info-color: #909399;
		--bg-color: #f5f7fa;
		--card-bg: #ffffff;
		--border-color: #ebeef5;
		--text-color: #303133;
		--text-secondary: #606266;
		--text-tertiary: #909399;
	}

	/* 页面整体样式 */
	.goods-type-manage {
		padding: 24px;
		background-color: var(--bg-color);
		min-height: 100vh;
		box-sizing: border-box;
	}

	/* 响应式布局优化 */
	@media (max-width: 768px) {
		.goods-type-manage {
			padding: 16px;
		}

		.page-header {
			flex-direction: column;
			align-items: flex-start;
		}

		.header-actions {
			margin-top: 16px;
		}

		.action-buttons {
			gap: 8px;
		}

		.action-btn {
			padding: 0 15px;
			font-size: 12px;
		}
	}

	/* 页面头部样式 */
	.page-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24px;
		gap: 20px;
	}

	.header-content {
		display: flex;
		flex-direction: column;
		gap: 8px;
	}

	.page-title {
		font-size: 24px;
		font-weight: 600;
		color: var(--text-color);
		margin: 0;
	}

	.page-subtitle {
		font-size: 14px;
		color: var(--text-secondary);
		margin: 0;
	}

	.header-actions {
		display: flex;
		gap: 10px;
	}

	/* 搜索卡片样式 */
	.search-card {
		margin-bottom: 16px;
		background-color: var(--card-bg);
		border-radius: 10px;
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
		transition: all 0.3s ease;
	}

	.search-card:hover {
		box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
	}

	.search-form {
		padding: 20px;
	}

	/* 操作按钮样式优化 */
	.action-buttons {
		display: flex;
		gap: 12px;
		flex-wrap: wrap;
	}

	.action-btn {
		height: 40px;
		font-size: 14px;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 8px;
		transition: all 0.2s ease;
		padding: 0 20px;
		border-radius: 6px;
		box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
	}

	.action-btn:hover {
		transform: translateY(-2px);
		box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
	}

	.action-btn-small {
		margin-right: 4px;
	}

	/* 表格卡片样式 */
	.table-card {
		background-color: var(--card-bg);
		border-radius: 10px;
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
		margin-bottom: 24px;
		overflow: hidden;
		transition: all 0.3s ease;
	}

	.table-card:hover {
		box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
	}

	.table-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16px 24px;
		border-bottom: 1px solid var(--border-color);
		background-color: #f9fafc;
	}

	.table-title {
		font-size: 18px;
		font-weight: 500;
		color: var(--text-color);
	}

	/* 图标样式 */
	.icon-container {
		display: flex;
		justify-content: center;
	}

	/* 表格行高和间距优化 */
	.el-table__row {
		height: 56px;
		transition: background-color 0.2s ease;
	}

	.el-table__row:hover {
		background-color: #f9fafc;
	}

	.el-table__cell {
		padding: 0 16px;
		vertical-align: middle;
		font-size: 14px;
		color: var(--text-color);
	}

	.el-table th {
		background-color: #f0f2f5;
		font-weight: 500;
		color: var(--text-color);
	}

	/* 操作按钮组样式 */
	.el-button-group .el-button {
		margin-right: 4px;
	}

	/* 对话框样式优化 */
	.el-dialog__header {
		background-color: #f9fafc;
		border-bottom: 1px solid #ebeef5;
	}

	.el-dialog__title {
		font-size: 16px;
		font-weight: 500;
		color: var(--text-color);
	}

	.el-dialog__body {
		padding: 30px 20px;
	}

	.el-form-item {
		margin-bottom: 20px;
	}
</style>